import React, {Component} from 'react';
import {Image, StyleSheet, Text, TextInput, TouchableOpacity, View, Alert, AsyncStorage} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {RadioButtons} from 'react-native-radio-buttons';
import CheckBox from 'react-native-check-box';
import {NavigationActions} from 'react-navigation';
import Toast from '@remobile/react-native-toast';
import WebIM from './../utils/Lib/WebIM';
import {api} from './../utils/Lib/WebIM';
import FetchUtils from './../utils/FetchUtils';
import utils from './../utils/utils';
import Spinner from "react-native-loading-spinner-overlay";

export default class RegisterPageThree extends Component {

    constructor(props) {
        super(props);
        this.datathree = {
            keyword: [],
            styleValue: [],
            priceValue: '',
        };
        this.state = {
            listKeyword: null,
            listStyle: null,
            viewKeyword: null,
            viewPrice: null,
            viewStyle: null,
            registerButStatus: false,
            loadingStatus: false,
        }
    }

    componentDidMount() {
        FetchUtils.get(utils.apiUrl + "/category/mark", null, (res) => {
            if (res.code === 200) {
                this.setState({
                    listKeyword: res.apiData.listKeyword,
                    listStyle: res.apiData.listStyle,
                    listPrice: res.apiData.listPrice,
                })
            }
        })
    }

    /*生成keyword标签*/
    getKeyword() {
        let keywordView = [];
        for (let n = 0; n < this.state.listKeyword.length; n++) {
            keywordView.push(
                <CheckBox
                    key={n}
                    ref={'keyword-' + n}
                    onClick={() => this.clickKeyword("keyword-", n, this.state.listKeyword[n].title)}
                    leftText={null}
                    checkedImage={
                        <Text
                            style={[styles.selectText, {
                                borderWidth: utils.autoWidth(1),
                                borderColor: '#010101'
                            }]}>{this.state.listKeyword[n].title}</Text>
                    }
                    unCheckedImage={
                        <Text style={styles.selectText}>{this.state.listKeyword[n].title}</Text>
                    }
                />
            )
        }
        return keywordView;
    };

    /*生成价格标签*/
    getPrice() {
        /*价格单选框*/
        let priceMark = [];
        for (let n = 0; n < this.state.listPrice.length; n++) {
            priceMark.push(this.state.listPrice[n].title)
        }
        return priceMark;
    }

    /*生成style标签*/
    getStyleMark() {
        let styleView = [];
        for (let n = 0; n < this.state.listStyle.length; n++) {
            styleView.push(
                <CheckBox
                    key={n}
                    ref={'stylemark-' + n}
                    onClick={() => this.clickKeyword("stylemark-", n, this.state.listStyle[n].title)}
                    leftText={null}
                    checkedImage={<Text style={[styles.selectText, {
                        borderWidth: utils.autoWidth(1),
                        borderColor: '#010101'
                    }]}>{this.state.listStyle[n].title}</Text>}
                    unCheckedImage={<Text style={styles.selectText}>{this.state.listStyle[n].title}</Text>}
                />
            )
        }
        return styleView;
    }


    /*标签处理*/
    async clickKeyword(name, index, value) {
        let ckeyword = this.refs[name + index];
        let keywordStatus = ckeyword.state.isChecked;
        let myData;
        if (name === 'keyword-') {
            myData = this.datathree.keyword;
        } else if (name === 'stylemark-') {
            myData = this.datathree.styleValue;
        }

        if (!keywordStatus) {
            myData.push(value);

        } else if (keywordStatus) {
            utils.removeByValue(myData, value);
            if (utils.isInArray(myData, value)) {
                utils.removeByValue(myData, value)
            }

        }
    }

    /*价格标签处理方法*/
    renderOption(option, selected, onSelect, index) {
        const styleText = selected ? {borderWidth: utils.autoWidth(1), borderColor: '#010101'} : {};
        return (
            <TouchableOpacity onPress={onSelect} key={index}>
                <Text style={[styles.selectText, styleText]}>{option}</Text>
            </TouchableOpacity>
        );
    }

    renderContainer(optionNodes) {
        return <View style={styles.selectTextView}>{optionNodes}</View>;
    }

    setSelectedOption(selectedOption) {
        this.datathree.priceValue = selectedOption;
        /*价格标签处理方法*/
    }

    /*注册按钮,防止多次点击*/
    registerBut = async () => {
        if (!this.state.registerButStatus) {
            // console.log(this.state.registerButStatus)
            await this.setState({registerButStatus: true,})
            setTimeout(async () => {
                await this.setState({registerButStatus: false})
            }, 1500);

            if (this.datathree.keyword.length == 0) {
                Alert.alert("警告", "请选择KEYWORD")
            } else if (this.datathree.styleValue.length == 0) {
                Alert.alert("警告", "请选择STYLE")
            } else if (this.datathree.priceValue == '') {
                Alert.alert("警告", "请选择PRICE")
            } else {
                let param = {
                    dataone: this.props.navigation.state.params.dataone,
                    datatwo: this.props.navigation.state.params.datatwo,
                    datathree: this.datathree,
                };
                this.setState({
                    loadingStatus: true,
                });
                await FetchUtils.postWithParams(utils.apiUrl + '/user/register', JSON.stringify(param), (res) => {
                    console.log(res);
                    if (res.code === 200) {
                        let params = [
                            ['XToken', res.apiData.XToken],
                            ["role", res.apiData.role],
                            ["username", res.apiData.username],
                            ["userId", res.apiData.userId],
                            ["avatar", res.apiData.avatar],
                        ];
                        AsyncStorage.multiSet(params, (error) => {
                            console.log(res);
                            if (error) {
                                console.log(error)
                            } else {
                                console.log('存值成功!');
                                this._HXregister(param.dataone.userName);
                            }
                        });
                    } else {
                        Alert.alert("警告", res.apiData);
                    }
                });
            }

        } else {
            Alert.alert("警告", "点击频繁")
        }
    };

    /*环信注册*/
    _HXregister = (username) => {
        let options = {
            username: username,
            password: username,
            nickname: username,
        };
        api.register(options).then((data) => {
            console.log(data);
            if (data.error) {
                Toast.showShortCenter('注册失败：' + data.error_description);
                return;
            }
            this._registerHXListener();
            this._loginToHX(username);
            Toast.showShortCenter('注册成功');
        });
    };

    // 登录环信聊天服务器
    _loginToHX = (username) => {
        if (WebIM.conn.isOpened()) {
            WebIM.conn.close('logout');
        }
        // 下面调用成功后，会回调SplashScreen中注册的listener
        WebIM.conn.open({
            apiUrl: WebIM.config.apiURL,
            user: username,
            pwd: username,
            appKey: WebIM.config.appkey,
            success: function (token) {
                console.log(token)
            },
            error: function () {
                Toast.showShortCenter('登录服务器出错!');
            }
        });
    };

    // 注册环信的消息监听器
    _registerHXListener() {
        WebIM.conn.listen({
            // xmpp连接成功
            onOpened: (msg) => {
                console.log(msg);
                if (msg.accessToken) {
                    AsyncStorage.setItem("HXToken", msg.accessToken, (error) => {
                        if (error) {
                            console.log("存值失败" + error)
                        } else {
                            console.log("存值成功");
                            const resetAction = NavigationActions.reset({
                                index: 0,
                                actions: [
                                    NavigationActions.navigate({routeName: 'MainTabNav'})
                                ]
                            });
                            this.props.navigation.dispatch(resetAction);
                        }
                    })
                }
            },
            onError: (error) => {
                console.log(error)
            },
        });
    }

    render() {
        /*生成keyword标签*/
        let keywordView = this.state.listKeyword ? this.getKeyword() : <Text>无数据</Text>;
        /*生成style标签*/
        let styleView = this.state.listStyle ? this.getStyleMark() : <Text>无数据</Text>;
        /*生成价格标签*/
        let priceMark = null;
        if (this.state.listPrice) {
            priceMark = this.getPrice();
        }
        let priceView = this.state.listPrice ?
            <RadioButtons
                options={priceMark}
                onSelection={this.setSelectedOption.bind(this)}
                renderOption={this.renderOption}
                renderContainer={this.renderContainer}
            />
            :
            <Text>无数据</Text>;


        return (
            <View style={styles.pageView}>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>

                <KeyboardAwareScrollView showsVerticalScrollIndicator={false}
                                         showsHorizontalScrollIndicator={false}>
                    <View style={styles.lineView}>
                        <View>
                            <Image source={require('../../img/header_line33x.png')} style={styles.lineViewImg}/>
                        </View>
                    </View>

                    <View style={styles.profileView}><Text style={styles.textProfile}> 风格信息（3/3）</Text></View>

                    <View style={styles.selectedView}>

                        <View style={styles.keywordView}>
                            <View style={styles.keywordTitleBigView}>
                                <View style={styles.keywordTitleView}>
                                    <View style={styles.keywordTitlePicView}></View>

                                    <View>
                                        <Text style={styles.keywordText}>KEYWORD</Text>
                                    </View>
                                </View>
                            </View>

                            <View style={styles.selectTextView}>
                                {keywordView}
                            </View>
                        </View>

                        <View style={styles.styleView}>
                            <View style={styles.keywordTitleBigView}>
                                <View style={styles.keywordTitleView}>
                                    <View style={styles.keywordTitlePicView}></View>

                                    <View>
                                        <Text style={styles.keywordText}>STYLE</Text>
                                    </View>
                                </View>
                            </View>

                            <View style={styles.selectTextView}>
                                {styleView}
                            </View>
                        </View>

                        <View style={styles.styleView}>
                            <View style={styles.keywordTitleBigView}>
                                <View style={styles.keywordTitleView}>
                                    <View style={styles.keywordTitlePicView}></View>

                                    <View>
                                        <Text style={styles.keywordText}>PRICE</Text>
                                    </View>
                                </View>
                            </View>

                            <View style={styles.selectTextView}>
                                {priceView}
                            </View>
                        </View>

                    </View>

                    <View style={styles.registerView}>
                        <TouchableOpacity style={styles.nextTouch}
                                          onPress={this.registerBut.bind(this)}>
                            <View style={styles.nextTouchTextView}><Text style={styles.nextTouchText}>注册</Text>
                                <Text style={styles.nextTouchText}>CREATE ACCOUNT</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    pageView: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#FFFFFF',
    },
    lineView: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
    },
    lineViewImg: {
        width: utils.autoWidth(200),
        height: utils.autoheight(15),
    },
    profileView: {
        alignItems: 'center',
    },
    textProfile: {
        fontSize: utils.setSpText(13),
        color: "#010101",
    },
    selectedView: {
        flexDirection: 'column',
        justifyContent: 'flex-start',
    },
    keywordView: {
        marginTop: utils.autoheight(14),
        flexDirection: 'column',
        justifyContent: 'flex-start',
    },
    keywordTitleBigView: {
        flexDirection: 'row',
    },
    keywordTitleView: {
        flexDirection: 'row',
    },
    keywordTitlePicView: {
        width: utils.autoWidth(7),
        height: utils.autoheight(25),
        backgroundColor: '#010101',
        marginRight: utils.autoWidth(8, 5),
    },
    keywordText: {
        fontSize: utils.setSpText(17),
        color: '#010101',
    },
    selectTextView: {
        marginLeft: utils.autoWidth(20),
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    selectText: {
        fontSize: utils.setSpText(15),
        color: '#000000',
        backgroundColor: '#F6F6F6',
        marginTop: utils.autoheight(15),
        marginRight: utils.autoWidth(15),
        paddingTop: utils.autoheight(5),
        paddingRight: utils.autoWidth(7.5),
        paddingBottom: utils.autoheight(5),
        paddingLeft: utils.autoWidth(7.5),
    },
    styleView: {
        marginTop: utils.autoheight(14),
    },
    registerView: {
        alignItems: 'center',
    },
    nextTouch: {
        width: utils.autoWidth(320),
        height: utils.autoheight(50),
        borderColor: '#010101',
        borderWidth: utils.autoWidth(2),
        alignItems: 'center',
        marginTop: utils.autoheight(16),
        marginBottom: utils.autoheight(33),

    },
    nextTouchTextView: {
        alignItems: 'center',
    },
    nextTouchText: {
        fontSize: utils.setSpText(17),
        color: '#010101',
    }
})